<template>
  <div class="content">
    <div class="header">
      <img class="a" src="../assets/left.png" alt @click="go()" />
      <p>乘车码</p>
      <img class="b" @click="isios==false?showTell():callIos(999999)" src="../assets/serve.png" alt />
      <van-popup
        class="popup showtell"
        v-model="isshowtell"
        round
        position="bottom"
        :style="{ height: '16%' }"
      >
        <!-- 电话 -->
        <van-button type="primary" class="photo" v-if="isios==false" @click="callPhone(12345)">
          <img src="../assets/tellicon.png" class="bgName" alt />
          <span>呼叫 （025）6738 2908</span>
        </van-button>
        <van-button type="primary" @click="isshowtell=false">取消</van-button>
      </van-popup>
    </div>

    <div class="tabs">
      <div class="tab" :class="{on:isTable==1}" @click="changeisTab(1)">
        <img src="../assets/metro_on.png" v-if="tabIndex==0" alt />
        <img src="../assets/metro.png" v-else alt />
        地铁
      </div>
    </div>

    <div class="info" v-if="isTable">
      <div class="tabBottom">
        <span :class="{show:tabIndex==0}">
          <div></div>
        </span>
      </div>
      <div class="ewm" @click="throttle()">
        <div v-if="isSuccess">
          <img :src="qrimagesrcs" alt />
          <img class="logoicon" :src="logoPath" alt />
        </div>
        <div v-else class="ewmtitle">{{ewmtitles}}</div>
      </div>

      <!-- <p class="ewm1">请点击乘车码刷新</p> -->
    </div>
    <div class="warning" v-else>
      <img src="../assets/icon4.png" alt class="icon4" />
      <div class="_info">您已暂停乘车码服务，点击下方按钮前往开启服务</div>
      <van-button block @click="Status(1)">确认开启</van-button>
    </div>
    <div class="twobtn">
      <van-button :disabled="disabled" @click="$router.push('/log')">
        <p>乘车记录</p>
      </van-button>
      <b></b>
      <van-button :disabled="disabled" @click="$router.push('/busCode')">
        <p>更多服务</p>
      </van-button>
    </div>
    <van-dialog
      v-model="show3"
      title
      show-cancel-button
      confirmButtonText="确认"
      confirmButtonColor="“#0064F4”"
      @close="gohome()"
    >
      <div class="textdialog">您已关闭地铁码服务，点击确认重新开启</div>
    </van-dialog>
    <div class="foot">
      <p>我的南京 • 银联 • 南京地铁</p>
    </div>
  </div>
</template>
<script>
import { getUserStatus } from "../api";
import { AESDecrypt } from "../utils/crypto";
import { register } from "../api";
import { UserStatus } from "../api";
import "../utils/tools";
export default {
  data() {
    return {
      show: false,
      checked: false,
      tabIndex: 0,
      isLogin: false,
      isUnlock: false,
      isKnow: false,
      showl: false,
      isshowtell: false,
      isTable: true,
      show3: false,
      qrimagesrcs: "",
      isios: false,
      lastTime: 0, //默认上一次点击时间为0
      disabled: false,
      logoPath: require("../assets/cardLogo1.png"), //中间logo的地址
      isSuccess: true,
      ewmtitles: "网络异常，请点击重新获取乘车码"
    };
  },
  // components: { VueQr },
  created() {
    // 判断当前设备为安卓还是ios
    const u = navigator.userAgent;
    const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    if (isiOS) {
      console.log("ios");
      this.isios = true;
      return "ios";
    } else {
      console.log("andriod");
      this.isios = false;
      return "andriod";
    }
  },
  mounted() {
    //调用禁止截屏方法
    try {
      znmh.disableScreenshot();
    } catch (e) {
      console.log(`您未安装我的南京最新版，请安装。错误:${e}`);
    }
    //判断是不是注册二维码状态
    let pp = localStorage.getItem("pp");
    if (pp == 1) {
      localStorage.removeItem("pp");
      // console.log(`${this.$route.query}哈哈`);
      //获取query参数并解密
      let { code, merId } = this.$route.query;
      let code1 = AESDecrypt(code);
      if (code1 == "0000") {
        //调用注册接口，查看状态接口，获取二维码
        this.postregister();
      } else {
        alert("乘车码开通失败");
      }
    } else {
      //判断是不是暂停状态
      let add = localStorage.getItem("add");
      if (add == 1) {
        this.isTable = false;
        localStorage.removeItem("add");
        this.disabled = true;
      } else {
        var appId = "cs_dtccm";
        // 发起请求（获取accessToken）
        this.$token(appId);
        //获取二维码
        this.getQrcode();
      }
    }
  },
  //页面关闭，禁止截图关闭
  beforeRouteLeave(to, form, next) {
    try {
      znmh.enableScreenshot();
    } catch (e) {}
    next();
  },
  //跳转页面，禁止截图关闭
  deactivated() {
    znmh.enableScreenshot();
  },
  methods: {
    postregister() {
      let idType = "01";
      let userType = "00";
      let isOpebWallet = "1";
      let data = localStorage.getItem("data");
      //调用后端接口
      register(data, idType, userType, isOpebWallet).then(res => {
        var appId = "cs_dtccm";
        // 发起请求（获取accessToken）
        this.$token(appId);
        this.getQrcode();
      });
    },
    throttle() {
      //获取当前时间的时间戳
      let now = new Date().valueOf();
      //第一次点击
      if (this.lastTime == 0) {
        console.log("触发事件");
        this.lastTime = now;
        this.getQrcode();
      } else {
        if (now - this.lastTime > 3000) {
          this.lastTime = now;
          console.log("间隔大于3秒，触发方法");
          this.getQrcode();
        } else {
          console.log("不触发");
        }
      }
    },
    // 调用拨号功能
    callPhone(phoneNumber) {
      window.location.href = "tel://" + phoneNumber;
    },
    callIos(phoneNumber) {
      window.location.href = "tel://" + phoneNumber;
    },
    Status(status) {
      let user_id = localStorage.getItem("user_id");
      localStorage.setItem("status", status);
      UserStatus(user_id, status).then(res => {
        console.log(res);
        if (res.data.respCode === "0000") {
          this.isTable = true;
          this.disabled = false;
          this.getQrcode();
        } else {
          alert(`开启失败：错误${res.data.respCode}`);
        }
      });
    },
    // getUnion() {
    //   let _this = this;
    //   //获取当前时间的时间戳
    //   let now1 = new Date().valueOf();
    //   window.znmh.getUnionCityList();

    //   window.getUnionCityListCallback = function(result) {
    //     let lastTime1 = new Date().valueOf();
    //     let times1 = lastTime1 - now1;
    //     console.log("获取城市接口：" + times1 + "ms");
    //     let resultJson = JSON.parse(result);
    //     if (resultJson.success) {
    //       let resultData = resultJson.result;
    //       let resData = decodeURIComponent(resultData);
    //       resData = JSON.parse(resData);
    //       let qrcodeval = {
    //         cityCode: resData[0].cityId,
    //         serviceScope: resData[0].serviceList[0].serviceScope
    //       };
    //       qrcodeval = JSON.stringify(qrcodeval);
    //       console.log(qrcodeval);
    //       localStorage.setItem("qrcodeval", qrcodeval);
    //       // window.znmh.getUnionQrcode(qrcodeval);
    //       _this.getQrcode();
    //     } else {
    //       console.log(result);
    //     }
    //   };
    // }, },

    getQrcode() {
      let _this = this;
      //获取当前时间的时间戳
      let now2 = new Date().valueOf();
      let qrcodeval = {
        cityCode: "3201",
        serviceScope: "0100"
      };
      qrcodeval = JSON.stringify(qrcodeval);
      // let qrcodeval = localStorage.getItem("qrcodeval");
      // if (qrcodeval != "") {
      window.znmh.getUnionQrcode(qrcodeval);
      window.getUnionQrCodeCallback = function(result) {
        let lastTime2 = new Date().valueOf();
        let times2 = lastTime2 - now2;
        console.log("获取二维码接口：" + times2 + "ms");

        if (result != "") {
          let resultJson = JSON.parse(result);
          console.log(resultJson);
          if (resultJson.success == "true" || resultJson.success === true) {
            _this.isSuccess = true;
            let res = resultJson.result;
            let resDecoded = decodeURIComponent(res);
            let dataJSON = JSON.parse(resDecoded);
            let base64Str = dataJSON.qrcodeDataBase64;
            // let qrimage = document.getElementById("qrimage");
            let qrimagesrc = "data:image/jpg;base64," + base64Str;
            _this.qrimagesrcs = qrimagesrc;
          } else {
            _this.isSuccess = false;
          }
        } else {
          _this.isSuccess = false;
        }
      };
      // } else {
      //   _this.getUnion();
      // }
    },

    changeTab(index) {
      this.tabIndex = index;
    },
    showPopup() {
      this.showl = true;
    },
    showTell() {
      this.isshowtell = true;
    },
    go() {
      history.go(-1);
    },
    changeisTab(index) {
      this.isTable = index;
    },
    gohome() {
      this.$router.push("/home");
    },
    getUser(tokens) {
      getUserStatus(tokens).then(res => {
        console.log("获取当前状态");
        if (res.data.respCode === "0000") {
          if (res.data.data.status == 1) {
            localStorage.setItem("user_id", res.data.data.user_id);
          } else if (res.data.data.status == 2) {
            this.isTable = false;
            this.disabled = true;
          }
        } else if (res.data.respCode == 6001) {
          this.show3 = true;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.content {
  box-sizing: border-box;
  font-family: PingFangSC-Medium, PingFang SC;
  min-height: 100vh;
  background: linear-gradient(137deg, #318bff 0%, #1876ff 100%);
  padding: 21px 17px 10px 17px;
  .foot {
    width: 100%;
    display: flex;
    justify-content: center;
    p {
      height: 12px;
      font-size: 12px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 250;
      color: #ffffff;
      line-height: 12px;
      margin-top: 37px;
      margin-bottom: 14.5px;
    }
  }
  .textdialog {
    margin: 34px 0;
    text-align: center;
  }
  .warning {
    margin-top: 23px;
    border-radius: 10px;
    background-color: #fff;
    box-sizing: border-box;
    width: 100%;
    padding: 33px 19px;
    position: relative;
    text-align: center;
    .title {
      text-align: center;
      font-size: 16px;
      font-weight: 400;
      color: #ff4141;
    }
    .icon4 {
      width: 93px;
      height: 93px;
      margin: 25px 0;
    }
    ._info {
      font-size: 16px;
      font-weight: 400;
      color: #999;
      text-align: center;
      margin-bottom: 30px;
    }
    button {
      font-size: 16px;
      font-weight: 500;
      color: #0064f4;
      border-radius: 5px;
      border: 1px solid #0064f4;
    }
  }
  .header {
    display: flex;
    justify-content: space-between;
    margin-top: 8px;
    .showtell {
      font-size: 16px;
      background-color: transparent;
      padding: 16px;
      font-weight: 500;
      button {
        display: block;
        border-radius: 10px;
        background-color: #fff;
        width: 92%;
        color: #207cff;
        padding: 0 25px;
        img {
          width: 17px;
          height: 21px;
          margin-right: 13px;
        }
      }
      .photo {
        margin-bottom: 16px;
        .van-button__content {
          justify-content: flex-start;
          .van-button__text {
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
          }
        }
      }
    }

    .a {
      width: 22px;
      height: 22px;
    }
    .b {
      width: 22px;
      height: 19px;
    }
    p {
      height: 25px;
      font-size: 18px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 250;
      color: #ffffff;
      line-height: 25px;
      margin: 0;
    }
  }
  .tabs {
    display: flex;
    justify-content: center;
    overflow: hidden;
    .tab {
      width: 92px;
      height: 34px;
      line-height: 34px;
      border-radius: 17px;
      display: flex;
      justify-content: center;
      align-items: center;
      background-repeat: no-repeat;
      font-size: 18px;
      font-weight: 500;
      color: #fff;
      margin: 0 10px;
      margin-top: 18px;
      &.on {
        background-color: #fff;
        color: #0064f4;
      }
      img {
        margin-right: 8px;
        width: 18px;
        height: 18px;
      }
    }
  }
  .info {
    margin-top: 23px;
    border-radius: 10px;
    background-color: #fff;
    box-sizing: border-box;
    width: 100%;
    padding: 33px 19px;
    position: relative;
    .tabBottom {
      margin: 0 -19px;
      width: 100%;
      height: 16px;
      position: absolute;
      top: 0px;
      color: #fff;
      font-size: 60px;
      display: flex;
      justify-content: center;
      span {
        display: block;
        text-align: center;
        width: 92px;
        margin: 0 10px;
        display: flex;
        justify-items: center;
        align-items: center;
        opacity: 0;
        div {
          width: 0;
          height: 0;
          border: 13px solid #fff;
          transform: translateX(32px) rotate(45deg);
        }
        &.show {
          opacity: 1;
        }
      }
    }
    .ewm {
      width: 240px;
      height: 240px;
      margin: 0 auto;
      position: relative;
      .logoicon {
        widows: 20px;
        height: 20px;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -10px;
        margin-left: -10px;
      }
    }
    .ewmtitle {
      width: 100%;
      height: 240px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 16px;
    }
    .ewm1 {
      width: 96px;
      height: 16.5px;
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 200;
      color: #999999;
      line-height: 16.5px;
      margin: 15.5px auto;
    }
  }
  .twobtn {
    display: flex;
    margin-top: 15px;
    border-radius: 10px;
    width: 343px;
    height: 45px;
    background: #ffffff;
    b {
      margin-top: 12.5px;
      width: 1px;
      height: 20px;
      background: #959595;
      border-radius: 10px;
    }
    button {
      width: 171.5px;
      border: none;
      border-radius: 10px;
      p {
        height: 22.5px;
        font-size: 16px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 250;
        color: #666666;
        line-height: 22.5px;
      }
    }
  }
}
</style>